package com.devoteam.shacts;


import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ShareContacts extends ListActivity {

	private final Context context = this;
	private Cursor vCursor;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//the contact list...
		vCursor = Shacts.getVCursor();
		//...displayed by contacts' name
		String[] columns = new String[] { ContactsContract.Contacts.DISPLAY_NAME };
		int[] to = new int[] { R.id.mtext };
		SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this, R.layout.list_contacts, vCursor, columns, to);
		this.setListAdapter(mAdapter);

		ListView lv = getListView();
		lv.setBackgroundColor(Color.WHITE);
		lv.setCacheColorHint(Color.TRANSPARENT);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				vCursor.moveToPosition(position);
					
				try{
					String name = vCursor.getString(vCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String contactId = vCursor.getString(vCursor.getColumnIndex(ContactsContract.Contacts._ID));
					String theVcard = VCardFactory.makeVCardString(context, name, contactId);

					//we start the barcode scanner activity to encode a string to a QR
					Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
					intent.putExtra("ENCODE_DATA", theVcard);
					intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
					startActivity(intent);

				}catch (ActivityNotFoundException e) {
					Toast.makeText(context, context.getString(R.string.er_barcode), Toast.LENGTH_LONG).show();
				}
				catch(Exception e){
					Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
				}

			}
		});
	}
}

